#!/usr/bin/env python
import openstack
from flask import current_app


def run():
    openstackAuthConfig = {
        "project_id": list(current_app.config["USER_TO_OPENSTACK"].keys())[0],
        "user_domain_name": "Default",
        "username": "demo",
        "password": "demodemo.123123",
        "auth_url": "http://172.16.3.203:5000/v3",
    }

    conn = openstack.connect(auth=openstackAuthConfig, auth_type="password")

    images = conn.image.images()
    for image in images:
        image_name = image.name
        list1 = image_name.split("-")
        name, imgtype, flavor_size, ip = list1
        flavor_name = "2-2-" + flavor_size[:-1]

        flavor = conn.compute.find_flavor(flavor_name)

        if "场景" in image_name:

            with open(
                r"C:\Users\wr\PycharmProjects\pythonProject1\adp\configs\template_images_list.yaml",
                "a",
                encoding="utf-8",
            ) as f:
                f.writelines("                    " + image.id + ":\n")
                f.writelines("                      name:" + " " + "'%s'" % name + "\n")
                f.writelines(
                    "                      flavor:" + " " + "'%s'" % flavor.id + "\n"
                )
                f.writelines(
                    "                      type:" + " " + "'%s'" % imgtype + "\n"
                )
                f.writelines("                      v4_fixed_ip:" + " " + '"%s"\n' % ip)
        else:

            with open(
                r"C:\Users\wr\PycharmProjects\pythonProject1\adp\configs\config.yaml",
                "a",
                encoding="utf-8",
            ) as f:
                f.writelines("                    " + image.id + ":\n")
                f.writelines("                      name:" + " " + "'%s'" % name + "\n")
                f.writelines(
                    "                      flavor:" + " " + "'%s'" % flavor.id + "\n"
                )
                f.writelines(
                    "                      type:" + " " + "'%s'" % imgtype + "\n"
                )


if __name__ == "__main__":
    run()
